package com.meila.cms.services.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.meila.cms.dao.CarDesignMapper;
import com.meila.cms.dao.PartListDesignMapper;
import com.meila.cms.entity.AjaxObj;
import com.meila.cms.entity.PartListDesign;
import com.meila.cms.model.CarDesignModel;
import com.meila.cms.model.PartListDesignModel;
import com.meila.cms.services.IPartListDesignService;
import com.meila.cms.util.DictUtil;
import com.meila.cms.util.HtmlUtil;
import com.meila.cms.util.ResourceLoader;
import com.meila.cms.util.freemark.HtmlGenerator;
import com.meila.cms.util.json.JsonUtil4;
import com.meila.cms.util.pdf.PdfDocumentGenerator;
 

@Service
public class PartListDesignService  extends BaseService implements IPartListDesignService {

	private final static HtmlGenerator htmlGenerator;
	static {
		htmlGenerator = new HtmlGenerator();
	}
	
 
	@Override
	public PartListDesignModel partListDesign(PartListDesign partListDesign) {
		// TODO Auto-generated method stub
		
		CarDesignModel carDesignModel=carDesignMapper.selectByPrimaryKey(partListDesign.getDesignid());
		
		Integer[] partsType={1,2,3,4,5};
		String [] partsTypeName={"内外饰","底盘","电器","车身","车身附件"};
		
		PartListDesignModel partListDesignModel = new PartListDesignModel();
		partListDesignModel.setDesignid(partListDesign.getDesignid());
		partListDesignModel.setCarid(carDesignModel.getCarid());
		
		List<Map<String, Object>> list = new ArrayList<>();
		
		int sum=0;
		for (int i = 0; i < partsType.length; i++) {
			
			WeakHashMap map=new WeakHashMap();
			partListDesign.setPartstype(partsType[i]);
			partListDesign.setCarid(carDesignModel.getCarid());
			List<PartListDesign> list2=partListDesignMapper.findPartListDesign(partListDesign);
			map.put("list", list2);
		    sum=partListDesignMapper.findPartListDesignSum(partListDesign);
			map.put("sum", sum);
			list.add(map);
			map.put("partsTypeName", partsTypeName[i]);
			map.put("partsType", partsType[i]);
 
		}
		
		partListDesignModel.setValueList(list);
		partListDesignModel.setAlias(carDesignModel.getAlias());
		
		partListDesign.setPartstype(null);
		sum=partListDesignMapper.findPartListDesignSum(partListDesign);
		partListDesignModel.setTotalprice(sum);
		
		partListDesignModel.setCartype(dictUtil.getNameByValue("CarType", carDesignModel.getCartype().toString()));
		
		return partListDesignModel;
	}

	@Override
	public Boolean addPartListDesign(PartListDesignModel partListDesignModel) {
		// TODO Auto-generated method stub
		try {
			 
			partListDesignMapper.insertSelective(partListDesignModel);
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
			// TODO: handle exception
		}
		
		return true;
	}

	@Override
	public AjaxObj delpart(String ids) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		String id[]=ids.split(",");
		try {
			PartListDesign partListDesign;
			for (int i = 0; i < id.length; i++) {
				
				partListDesign = new PartListDesign();
				partListDesign.setId(Integer.valueOf(id[i]));
				partListDesign.setUpdatetime(new Date());
				partListDesign.setDel(1);
				partListDesignMapper.updateByPrimaryKeySelective(partListDesign);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("删除失败");
		}

		ajaxObj.setMsg("删除成功");
		return ajaxObj;
	}

	@Override
	public AjaxObj saveEditPart(List<JSONObject> partListDesignModels) {
		// TODO Auto-generated method stub
		
		AjaxObj ajaxObj=new AjaxObj();
		try {
			for (JSONObject jSONObject : partListDesignModels) {
			 
				PartListDesign partListDesign=(PartListDesign) JsonUtil4.getInstance().json2obj(jSONObject.toJSONString(),PartListDesign.class);
				partListDesignMapper.updateByPrimaryKeySelective(partListDesign);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("保存失败");
			return ajaxObj;
		}

		ajaxObj.setMsg("保存成功");
		return ajaxObj;
	}

	@Override
	public ResponseEntity<byte[]> exportPDF(String  designid,HttpServletRequest request,HttpServletResponse response) {
		// TODO Auto-generated method stub
		
		
		AjaxObj ajaxObj=new AjaxObj();
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path = basePath+"front/carDesign/partListpdf?export=true&designid="+designid;
        // classpath 路径
    	String outputFileClass = ResourceLoader.getPath("");
    	
    	long timp=System.currentTimeMillis();
	    String    outputFile = new File(outputFileClass).getParentFile().getParent()+"\\resources\\download\\"+timp+".pdf";
       
	    HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
		try {
			PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
//	        System.out.println("-----------generate ok------------");
//	        new DownloadManager("d://partList.pdf",1,basePath+"resources/pdf/"+timp+".pdf").action();
//	        System.out.println("-----------download ok------------");
			
			//设置响应头，控制浏览器下载该文件
	        file = new File(outputFile);  
	        String fileName=new String("partList.pdf".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName);   
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   

	        result=  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                headers, HttpStatus.CREATED);
	        
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
 
		}
        return result;  
	 
	}

	
}
